<template>
  <!-- 富文本编辑器可以上传图片与粘贴图片并自动上传到服务器转换为在线地址 -->
  <div>
    <!-- 此处注意写法v-model:content -->
    <QuillEditor ref="myQuillEditor" :style="{ height: props.height }" theme="snow" v-model="data.content" :options="data.editorOption"
      contentType="html" @update:content="setValue()" />
    <!-- 使用自定义图片上传 -->
    <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" />
  </div>
</template>
<script setup>
import { QuillEditor, Quill } from '@vueup/vue-quill'
import { reactive, onMounted, ref, toRaw, watch } from 'vue'
import { REQUEST } from '@/api/request'
import ImageResize from 'quill-image-resize'; //导入插件
import '@vueup/vue-quill/dist/vue-quill.snow.css';
// 注册插件
Quill.register('modules/imageResize', ImageResize);
const props = defineProps({
  value: [String],
  height: {
    type: [String],
    default: '300px'
  },
})
watch(() => props.value, (val) => {
  toRaw(myQuillEditor.value).setHTML(val)
}, { deep: true })
const emit = defineEmits(['updateValue'])
const content = ref('')
const myQuillEditor = ref()
// 通过watch监听回显，这边使用v-model:content 不能正常回显
watch(() =>content.value, (val) => {
 console.log(val,'content')

}, { deep: true })
const fileBtn = ref()
const data = reactive({
  content: '',
  editorOption: {
    placeholder: '请输入内容',
    modules: {
      imageResize: {},
      toolbar: [
        ['bold', 'italic', 'underline'],    //加粗，斜体，下划线，删除线
        ['blockquote'],     //引用，代码块
        [{ 'header': 1 }, { 'header': 2 }],        // 标题，键值对的形式；1、2表示字体大小
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],     //列表
        
        // [{ 'script': 'sub' }, { 'script': 'super' }],   // 上下标
        [{ 'indent': '-1' }, { 'indent': '+1' }],     // 缩进
        [{ 'direction': 'rtl' }],             // 文本方向
        [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],     //几级标题
        [{ 'color': [] }, { 'background': [] }],     // 字体颜色，字体背景颜色
        // [{ 'font': [] }],     //字体
        [{ 'align': [] }],    //对齐方式
        // 行高
        // [{ 'height': [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100] }],
        ['clean'],    //清除字体样式
        ['image'] 
      ]
    },
  }
})
const imgHandler = (state) => {
  if (state) {
    fileBtn.value.click()
  }
}
const setValues = (v) => {
  if (v) {
    myQuillEditor.value.setHTML(v)
    data.content = v
  }else{
    const quill = toRaw(myQuillEditor.value).getQuill()
    quill.root.innerHTML = ''; // 清空编辑器内容（可选）
  }
}
defineExpose({ setValues,data})
// 抛出更改内容，此处避免出错直接使用文档提供的getHTML方法
const setValue = () => {
  const text = toRaw(myQuillEditor.value).getHTML()
  data.content = text
  content.value = text
  emit('updateValue', text)
}
const handleEditorReady = () => {
  const quill = toRaw(myQuillEditor.value).getQuill()
  quill.root.innerHTML = ''; // 清空编辑器内容（可选）
}
// 上传图片
const uploadImg = (files) => {
  const formdata = new FormData()
  formdata.append('file', files[0])
  REQUEST.UPLOAD('UPLOADFILE', formdata, {}).then(res => {
    if (res.data) {
      const quill = toRaw(myQuillEditor.value).getQuill()
      const length = quill.getSelection().index
      // 插入图片，res为服务器返回的图片链接地址
      quill.insertEmbed(length, 'image', res.data.url)
      // 调整光标到最后
      quill.setSelection(length + 1)
    }
  })
}


const handleUpload = (e) => {
  const files = Array.prototype.slice.call(e.target.files)
  if (!files) {
    return
  }
  uploadImg(files)
}
// 初始化编辑器
onMounted(() => {
  const quill = toRaw(myQuillEditor.value).getQuill()
  if (myQuillEditor.value) {
    quill.getModule('toolbar').addHandler('image', imgHandler)
    setTimeout(()=>{
      myQuillEditor.value.setHTML(props.value?props.value:'')
    },500)
  }


  window.addEventListener('paste', e => {
    // console.log(e.clipboardData)
    if (e.clipboardData && e.clipboardData.files && e.clipboardData.files.length) {
      e.preventDefault(); // 阻止默认行为即不让剪贴板内容在div中显示出来
      // 获取图片内容
      const files = e.clipboardData.files;
      uploadImg(files)
    } else {
      console.log("粘贴内容不是图片");
    }
  })
  toRaw(myQuillEditor.value).setHTML(props.value)

})
</script>

<style scoped lang="scss">
// 调整样式
:deep(.ql-editor) {
  min-height: 180px;
}

:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}
</style>
<style>
.editor {
  line-height: normal !important;
  height: 800px;
}
.ql-container{
  max-width: 800px!important;
  border-radius: 0 0 5px 5px;
}
.ql-toolbar.ql-snow{
  border-radius: 5px 5px 0px 0px;
}

.ql-snow .ql-tooltip[data-mode=link]::before {
  content: "请输入链接地址:";
}

.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: '保存';
  padding-right: 0px;
}

.ql-snow .ql-tooltip[data-mode=video]::before {
  content: "请输入视频地址:";
}
.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: '14px';
}

.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before {
  content: '10px';
}

.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before {
  content: '18px';
}

.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before {
  content: '32px';
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: '文本';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: '标题1';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: '标题2';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: '标题3';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: '标题4';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: '标题5';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: '标题6';
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: '标准字体';
}

.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=serif]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]::before {
  content: '衬线字体';
}

.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=monospace]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before {
  content: '等宽字体';
}

.ql-align-center {
  text-align: center;
}

.ql-align-right {
  text-align: right;
}

.ql-align-left {
  text-align: left;
}
</style>
